package com.zhou.juc.test01_thread;

/**
 * @author zhouyanxiang
 * @create 2020-06-2020/6/19-17:05
 */
public class T03_Sleep_Yield_Join {

    public static void testSleep(){
        new Thread(()->{
            for (int i = 0; i < 1000; i++) {
                System.out.println("test sleep");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * Thread.yield()方法作用是：暂停当前正在执行的线程对象，并执行其他线程。
     */
    public static void testYield(){
        new Thread(()->{
            for (int i = 0; i < 1000; i++) {
                System.out.println("A ------- " + i);
                if (i % 10 == 0){
                    Thread.yield();
                }
            }
        }).start();
        
        new Thread(()->{
            for (int i = 0; i < 1000; i++) {
                System.out.println("B ------ " + i);
                if (i % 10 == 0){
                    Thread.yield();
                }
            }
        }).start();
    }


    /**
     *   Thread.join()把指定的线程加入到当前线程，可以将两个交替执行的线程合并为顺序执行的线程。
     */
    public static  void testJoin() throws InterruptedException {
       Thread T1 = new Thread(()->{
           for (int i = 0; i < 10; i++) {
               System.out.println( "T1 ---- " + i);
               try {
                   Thread.sleep(500);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
       });

        Thread T2 = new Thread(()->{
            try {
                T1.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < 10; i++) {
                System.out.println( "T2 ---- " + i);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread T3 = new Thread(()->{
            try {
                T2.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < 10; i++) {
                System.out.println( "T3 ---- " + i);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        T1.start();
        T2.start();
        T3.start();
    }


    public static void main(String[] args) throws InterruptedException {
//        testSleep();
        testYield();
//        testJoin();
    }
}
